package com.pan.mapping;

import com.pan.entity.JavaSqlType;

import java.lang.reflect.Field;
import java.util.HashMap;

public class EntityToSQL<T>{


    private Class<T> entityClass;


    public EntityToSQL(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    public String createTable(String tableName, HashMap<String,JavaSqlType> nameTypeMap){
        Field[] fields = entityClass.getDeclaredFields();
        String content ="";
        for (Field f :fields) {
            if (!nameTypeMap.containsKey(f.getName())) throw  new RuntimeException("不存在该类型");
            if (content.length() == 0) {
                content += f.getName() + nameTypeMap.get(f.getName());
            }
            else{
                content += ",\n"+f.getName() + nameTypeMap.get(f.getName());
            }
        }


        String createSql = "create table "+ tableName+ "("
        +content
        +");";
        return createSql;
    }

    public String createTable(HashMap<String,JavaSqlType> nameTypeMap){
        String className = entityClass.getName();
        String[] names = className.split("\\.");
        String name = names[names.length-1];
        return this.createTable(name,nameTypeMap);
    }

    public String getInsert(T entity){
        String className = entityClass.getName();
        String[] names = className.split("\\.");
        String name = names[names.length-1];
        return this.getInsert(entity,name);
    }
    public String getInsert(T entity,String tableName){
        Field[] declaredFields = entityClass.getDeclaredFields();
        String names = "";
        String values = "";
        for (Field field : declaredFields){
            names += field.getName()+",";
            field.setAccessible(true);
            try {
                values += "\""+String.valueOf(field.get(entity))+"\",";
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        values = values.substring(0,values.length()-1);
        names = names.substring(0,names.length()-1);
        String insertSql = "insert into " + tableName + "("+names+") values ("+values+");";
        return insertSql;
    }
}
